<?php

namespace App\Http\Controllers\School;

use App\Http\Resources\School\OrderReviewResource;
use App\Models\BookOrder;
use App\Models\BookOrderReview;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class OrderReviewController
 * @package App\Http\Controllers\School
 * 订单审核 type 为 official
 */
class OrderReviewController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $bookOrders = BookOrder::orderBy('created_at', 'desc')
            ->where('school_id', \Auth::user()->school_id)
            ->with('rule')->with('user.role')->with('review')
            ->isOfficial()->selectStatus($request->status)
            ->reviewIs($request->is_review)
            ->eatTypeIs($request->eat_type)
            ->eatDateIs($request->eat_date)
            ->eatNameLike($request->eat_name)
            ->eatPhoneIs($request->eat_phone);
        if ($request->type === 'export') {
            $data = $bookOrders->get();
        } else {
            $data = $bookOrders->paginate($request->size);
        }
        return OrderReviewResource::collection($data);
    }

    /**
     * @param Request $request
     * @param BookOrder $orderReview
     * @return OrderReviewResource|array
     * @throws \Exception
     * 审核订单
     * 只有状态为已提交，并且审核状态为审核中的订单才能进行审核
     * 审核拒绝时，将订单状态也改为取消
     */
    public function update(Request $request, BookOrder $orderReview)
    {
        DB::beginTransaction();
        try {
            if ($orderReview->status != BookOrder::ORDER_STATUS_INIT) {
                throw new \Exception('只有状态为已提交的订单才能进行审核');
            }
            $bookOrderReview = BookOrderReview::where('order_id', $orderReview->id)->first();
            if ($bookOrderReview->status !== BookOrder::REVIEWING) {
                throw new \Exception('只能审核状态为审核中的订单');
            }
            $bookOrderReview->fill($request->all());
            $bookOrderReview->save();
            if ($bookOrderReview->status == BookOrder::NOT_REVIEWED) {
                // 审核拒绝时，将订单状态也改为取消
                $orderReview->status = BookOrder::ORDER_STATUS_CANCELED;
                $orderReview->save();
            }
            DB::commit();
            return new OrderReviewResource($orderReview);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->fail($exception->getMessage());
        }
    }
}
